<template>
  <div class="article-page">
    <nav class="my-nav van-hairline--bottom">
      <a :class="{ active: sorter === 'weight_desc'}" href="javascript:;" @click="sorter = 'weight_desc'">推荐</a>

      <a :class="{ active: sorter === null }" href="javascript:;" @click="sorter = null">最新</a>

      <div class="logo"><img src="@/assets/logo.png" alt="" /></div>
    </nav>
    <van-list v-model="loading" finished-text="没有更多了" @load="onLoadMore" :finished="isFinished">
      <ArticleItem v-for="item in list" :key="item.id" :item="item"  @click="$router.push('/article'+item.id)"/>
    </van-list>
  </div>
</template>

<script>
import { getArticleAPI } from '@/api/article'

export default {
  name: 'article-page',
  data () {
    return {
      list: [], // 列表数据
      loading: false, // 加载状态
      // 1.当前页数
      current: 1,
      // 6.是否还有更多数据
      isFinished: false,
      // 5.总页数
      pageTotal: 999,
      // 排序方式
      sorter: 'weight_desc'
    }
  },
  methods: {
    // 获取列表数据
    async loadData () {
      // 打开加载状态
      this.loading = true
      const res = await getArticleAPI({
        // 2.传入页码
        current: this.current,
        sorter: this.sorter,
        page_Total: this.pageTotal
      })
      // 追加数据
      this.list.push(...res.data.rows)
      // 关闭加载状态
      this.loading = false
      // 3.加载完毕，页码+1
      this.current++
      // 获取总页数
      this.pageTotal = res.data.pageTotal
      // 4.判断是否还有更多数据
      if (this.current > this.pageTotal) {
        this.isFinished = true
      }
    },
    // 下拉加载更多
    onLoadMore () {
      this.loadData()
    }
  },
  watch: {
    sorter () {
      this.list = []
      this.current = 1
      this.isFinished = false
      if (!this.loading) {
        this.loadData()
      }
    }
  }

}
</script>

<style lang="less" scoped>
.article-page {
  margin-bottom: 50px;
  margin-top: 44px;

  .my-nav {
    height: 44px;
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    z-index: 999;
    background: #fff;
    display: flex;
    align-items: center;

    > a {
      color: #999;
      font-size: 14px;
      line-height: 44px;
      margin-left: 20px;
      position: relative;
      transition: all 0.3s;

      &::after {
        content: "";
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        bottom: 0;
        width: 0;
        height: 2px;
        background: #222;
        transition: all 0.3s;
      }

      &.active {
        color: #222;

        &::after {
          width: 14px;
        }
      }
    }

    .logo {
      flex: 1;
      display: flex;
      justify-content: flex-end;

      > img {
        width: 64px;
        height: 28px;
        display: block;
        margin-right: 10px;
      }
    }
  }
}
</style>
